package org.hishenframework.core.web.upload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传类
 * upload()				controll				
 * clean()				清除临时目录方法  （可配置成定时任务）
 * @author zhangdi
 *
 */
@RequestMapping("/upload")
public class HishenUploader {

	/** 上传路径 */
	public static final String UPLOAD_PATH = "/resource/upload";

	private Logger logger = LoggerFactory.getLogger(HishenUploader.class);
	
	/** 文件生存时间 */
	private long liveTime = 60 * 60 * 24;
	
	@Resource
	private ServletContext servletContext;
	
	@ResponseBody
	@RequestMapping
	public String upload(HttpSession session, MultipartFile mfile) throws IOException {
		if (mfile == null) {
			return "";
		}
		//根据sessionid创建目录，session销毁时，该目录删除
		String sessionId = session.getId();
		String uuid = UUID.randomUUID().toString();
		
		//设置上传文件临时存放的绝对路径
		String realPath = servletContext.getRealPath("/");
		String relativePath = UPLOAD_PATH + "/" + sessionId + "/" + uuid;
		//创建目录
		File folder = new File(realPath, relativePath);
		folder.mkdirs();
		//设置文件名
		File file = new File(folder, mfile.getOriginalFilename());
		try (InputStream in = mfile.getInputStream()) {
			//拷贝文件
			FileUtils.copyInputStreamToFile(in, file);
		}
		String rt = relativePath + "/" + mfile.getOriginalFilename();
//		if (html4 != null) {
//			rt = "<script type=\"text/javascript\">" +
//					"parent.callback('" + rt + "');" +
//				"</script>";
//		}
		logger.debug(rt);
		return rt;
	}

	/**
	 * 清除文件夹
	 * @throws FileNotFoundException
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	public void clean() {
		//文件夹数量
		int folderCount = 0;
		//未删除数量
		int afterDelCount = 0;
		long now = new Date().getTime();
		String pathname = servletContext.getRealPath("/") + UPLOAD_PATH;
		File folder = new File(pathname);
		File[] listFiles = folder.listFiles();
		folderCount = listFiles.length;
		for (File subFolder : listFiles) {
			if (now - subFolder.lastModified() > liveTime) {
				try {
					FileUtils.deleteDirectory(subFolder);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		afterDelCount = folder.list().length;
		logger.debug("文件夹共有 " + folderCount + "个，删除后剩余 " + afterDelCount + " 个" );
	}

	public long getLiveTime() {
		return liveTime;
	}

	public void setLiveTime(long liveTime) {
		this.liveTime = liveTime;
	}
}
